package com.agileai.esb.smc.controller.sysres;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.controller.core.StandardEditHandler;
import com.agileai.hotweb.domain.FormSelect;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.MapUtil;
import com.agileai.esb.smc.bizmoduler.sysres.MqContainerManage;

public class MqContainerManageEditHandler
        extends StandardEditHandler {
    public MqContainerManageEditHandler() {
        super();
        this.listHandlerClass = MqContainerManageListHandler.class;
        this.serviceId = buildServiceId(MqContainerManage.class);
    }
    
	public ViewRenderer prepareDisplay(DataParam param) {
		String operaType = param.get(OperaType.KEY);
		if (isReqRecordOperaType(operaType)){
			DataRow record = getService().getRecord(param);
			this.setAttributes(record);
			if (!operaType.equals("insert")) {
				param.put("brokerId", record.getString("BROKER_ID"));
			}
		}
		this.setOperaType(operaType);
		processPageAttributes(param);
		return new LocalRenderer(getPage());
	}

    protected void processPageAttributes(DataParam param) {
        setAttribute("CONTAINER_TYPE",
                     FormSelectFactory.create("MQContainerType")
                                      .addSelectedValue(getOperaAttributeValue("CONTAINER_TYPE",
                                                                               "Queue")));
    	String brokerId = param.get("brokerId");
    	FormSelect brokerIdFormSelect = FormSelectFactory.create("mqresource.findRecords",new DataParam(),"BROKER_ID","BROKER_ALIAS");
    	setAttribute("brokerId",brokerIdFormSelect.addSelectedValue(brokerId));
    }
    
    @Override
	public ViewRenderer doCheckUniqueAction(DataParam param){
		String responseText = "";
		String operateType = param.get(OperaType.KEY);
		DataRow record = getService().checkUnique(param);
		if (OperaType.CREATE.equals(operateType)){
			if (!MapUtil.isNullOrEmpty(record)){
				responseText = defDuplicateMsg;
			}			
		}else if (OperaType.UPDATE.equals(operateType)){
			String primaryKey = getService().getPrimaryKey();
			String primaryKeyValue = param.get(primaryKey);
			
			if (!MapUtil.isNullOrEmpty(record) && !primaryKeyValue.equals(record.stringValue(primaryKey))){
				responseText = defDuplicateMsg;
			}
		}
		return new AjaxRenderer(responseText);
	}

    protected MqContainerManage getService() {
        return (MqContainerManage) this.lookupService(this.getServiceId());
    }
}
